import axios from 'axios';
import { Toast } from 'react-vant';
import store from '@/redux';
axios.defaults.baseURL = 'https://apif.java.crmeb.net';
axios.defaults.timeout = 60000;
// 请求拦截
axios.interceptors.request.use((config)=>{
    // 向请求头中添加token授权字段  // 获取redux中的token
    config.headers['Authori-Zation'] = store.getState().tokenReducer.token
    // 提示加载状态
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration:0
      })
    return config
})
// 响应拦截
axios.interceptors.response.use(res=>{
    // 取消加载提示
    Toast.clear();
    if(res.data.code===401){
        // token失效或未登录
        Toast(res.data.message);
        // 跳转到登录页面
        window.location.hash='#/login'
        return res
    }
    Toast.clear();
    return res
})
// 默认请求头
const defaultHeaders = {
    "Content-Type": "application/json"
}
let http = (url, data=null, method = 'get', headers = defaultHeaders) => {
    return axios({
        url,
        method,
        params: method === 'get' ? data : null,
        data: method !== 'get' ? data : null,
        headers,
    })
}

export default http;